package com.ruicar.afs.cloud.afscase.risk.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.risk.entity.CaseTortoiseApply;
import com.ruicar.afs.cloud.afscase.risk.service.CaseTortoiseApplyService;
import com.ruicar.afs.cloud.afscase.risk.service.CaseTortoiseService;
import com.ruicar.afs.cloud.afscase.risk.vo.ApplyExecuteParam;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.risk.api.enums.tortoise.GwtTortoiseStartApproveType;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description
 * @Author Peng Jinbo
 * @Date 2020/08/11 22:22
 */
@Slf4j
@RequestMapping("/tortoiseApply")
@RestController
@AllArgsConstructor
public class TortoiseApplyController {

    /**
     * Case tortoise apply service
     */
    private CaseTortoiseApplyService caseTortoiseApplyService;

    private CaseTortoiseService caseTortoiseService;

    /**
     * @param applyNo apply no
     * @return the newest apply notice
     * @Author Peng Jinbo Gets newest apply notice *
     */
    @GetMapping("/newest")
    public IResponse getNewestApplyNotice(@RequestParam("applyNo") String applyNo) {
        if (StrUtil.isBlank(applyNo)) {
            return IResponse.fail("申请编号不可为空");
        }
        CaseTortoiseApply tortoiseApply = caseTortoiseApplyService.list(
                Wrappers.<CaseTortoiseApply>lambdaQuery()
                        .eq(CaseTortoiseApply::getApplyNo, applyNo)
                        .orderByDesc(CaseTortoiseApply::getOperateDate)
        ).stream().findFirst().orElse(new CaseTortoiseApply());
        return IResponse.success(tortoiseApply);
    }

    /**
     * Author Peng Jinbo
     * Tortoise batch execute response
     *
     * @param param param
     * @return the response
     */
    @PostMapping("/batch")
    public IResponse tortoiseBatchExecute(@RequestBody ApplyExecuteParam param) {
        List<String> executeFailApplyNoList = new ArrayList<>();
        if (Objects.nonNull(param) && ArrayUtil.isNotEmpty(param.getApplyNos())) {
            for (String applyNo : param.getApplyNos()) {
                try {
                    caseTortoiseService.signalApply(applyNo,true,GwtTortoiseStartApproveType.NORMAL);
                } catch (Exception e) {
                    executeFailApplyNoList.add(applyNo);
                    log.error("申请编号：{}，玄武手动调用失败",applyNo, e);
                }
            }
        }
        if (executeFailApplyNoList.size() == 0) {
            return IResponse.success("操作成功!");
        } else {
            return IResponse.fail(String.format("申请编号{}，执行失败", executeFailApplyNoList));
        }
    }

}